﻿@{
    ViewData["Title"] = "货品类型管理";
}

<!-- 引入资源：Vue3、Axios、Element Plus -->
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<link rel="stylesheet" href="//unpkg.com/element-plus/dist/index.css" />
<script src="//unpkg.com/element-plus"></script>

<div id="app">
    <!-- 1. 查询条件区域 -->
    <div class="search-area">
        <label>货品类型：</label>
        <input type="text" v-model="searchParams.typeNameOrCode" placeholder="请输入货品类型名称/编号">

        <label>状态：</label>
        <el-select v-model="searchParams.status" placeholder="请选择" class="custom-select" style="width:90px">
            <el-option value="">全部</el-option>
            <el-option value="1">启用</el-option>
            <el-option value="0">停用</el-option>
        </el-select>

        <label>修改人：</label>
        <input type="text" v-model="searchParams.updateBy" placeholder="请输入" style="width:150px">

        <!-- 修改“操作时间”为日期范围选择器 -->
        <label>修改时间：</label>
        <el-date-picker v-model="searchParams.operationTimeRange"
                        type="daterange"
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                        style="width: 280px;"></el-date-picker>

        <button v-on:click="resetSearch($event)" class="reset-btn">重置</button>
        <button v-on:click="queryData($event)" class="query-btn">查询</button>
    </div>

    <!-- 2. 操作按钮区域 -->
    <div class="action-buttons">
        <el-button type="primary" v-on:click="addNew" style="background-color: #28a745; border-color: #28a745;">新增</el-button>
        <!-- 导入按钮：添加点击事件绑定 -->
        <el-button type="primary" v-on:click="openImportDialog">导入</el-button>
        <!-- 导入弹窗 -->
        <el-dialog v-model="importDialogVisible" title="导入货品类型" width="500px">
            <el-upload class="upload-excel"
                       action=""
                       :auto-upload="false"
                       :on-change="handleFileChange"
                       :show-file-list="true"
                       accept=".xlsx, .xls"
                       ref="upload">
                <el-button type="primary">选择Excel文件</el-button>
                <div slot="tip" class="el-upload__tip">
                    支持 .xlsx、.xls 格式，大小不超过5MB
                </div>
            </el-upload>
            <template #footer>
                <el-button v-on:click="importDialogVisible = false">取消</el-button>
                <el-button type="primary" v-on:click ="confirmImport">确认导入</el-button>
            </template>
        </el-dialog>
        <el-button plain v-on:click="exportData">导出</el-button>
    </div>

    <!-- 加载中提示 -->
    <el-loading v-loading="loading"
                element-loading-text="正在加载数据..."
                element-loading-spinner="el-icon-loading"
                element-loading-background="rgba(0, 0, 0, 0.7)">
        <div class="table-container">
            <el-table :data="goodsTypeList"
                      border
                      striped
                      style="width: 100%; margin-top: 10px;"
                      :header-cell-style="{ background: '#f5f7fa', color: '#333', fontWeight: 'bold' ,textAlign: 'center' }"
                      :cell-style="({ column }) => column.columnKey === 'goodsTypeNameColumn' ? { padding: '12px 8px', textAlign: 'left' } : { padding: '12px 8px', textAlign: 'center' }">
                <!-- 表格列定义 -->
                <el-table-column type="selection" width="55"></el-table-column>
                <el-table-column type="index" label="序号" width="60"></el-table-column>
                <el-table-column prop="goodsTypeCode" label="货品类型编号" width="190"></el-table-column>
                <el-table-column label="货品类型名称"
                                 width="180px"
                                 column-key="goodsTypeNameColumn">
                    <template #default="scope">
                        <span v-html="formatGoodsTypeName(scope.row, goodsTypeList)"></span>
                    </template>
                </el-table-column>
                <el-table-column prop="sortOrder" label="排序" width="80"></el-table-column>

                <el-table-column prop="status" label="状态" width="80">
                    <template #default="scope">
                        {{ scope.row.status == 1 ? '启用' : (scope.row.status == 0 ? '停用' : scope.row.status) }}
                    </template>
                </el-table-column>
                <el-table-column prop="remarks" label="备注" width="120"></el-table-column>
                <el-table-column prop="updateBy" label="修改人" width="100"></el-table-column>
                <el-table-column prop="updateTime"
                                 label="修改时间"
                                 width="200"
                                 :formatter="formatOperationTime"></el-table-column>
                <el-table-column label="操作" width="140">
                    <template #default="scope">
                        <div style="text-align: center;">
                            <el-button type="text" v-on:click="editItem(scope.row)">编辑</el-button>
                            <el-button type="text" v-on:click="deleteItem(scope.row)" style="color: #f56c6c;">删除</el-button>
                        </div>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <!-- 分页组件 -->
        <div class="pagination-container" style="margin-top: 15px; text-align: right;">
            <el-pagination v-model:current-page="pagination.pageNum"
                           v-model:page-size="pagination.pageSize"
                           :page-sizes="[10, 20, 50, 100]"  <!-- 可选每页条数 -->
      :total="pagination.total"        <!-- 总记录数 -->
      layout="total, sizes, prev, pager, next, jumper"  <!-- 分页布局 -->
                v-on:size-change="handlePageSizeChange"  <!-- 每页条数变化事件 -->
                v-on:current-change="handlePageNumChange"  <!-- 页码变化事件 -->
    ></el-pagination>
        </div>
    </el-loading>

    <!-- 新增抽屉（右侧弹出） -->
    <el-drawer :title="isEdit ? '编辑货品类型' : '新增货品类型'"
               v-model="addDrawerVisible"
               direction="rtl"
               size="50%">
        <el-form :model="form" label-width="80px" class="add-form" label-position="top">
            <!-- 第一行：上级分类（左） + 货品类型编号（中） + 货品类型名称（右） -->
            <el-row :gutter="24">
                <el-col :span="12">
                    <el-form-item label="上级分类" prop="parentCategory" required>

                        <el-select v-model="form.parentCategory" placeholder="请选择" class="full-width">
                            <el-option v-for="item in parentCategoryOptions"
                                       :key="item.goodsTypeId"
                                       :label="item.goodsTypeName"
                                       :value="item.goodsTypeId"
                                       :style="{ paddingLeft: `${item.level * 20}px` }"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="货品类型编号" prop="goodsTypeCode" required class="form-label ml-300">
                        <el-input v-model="form.goodsTypeCode" placeholder="自动获取系统编号" readonly class="full-width"></el-input>
                    </el-form-item>
                </el-col>

            </el-row>

            <el-row :gutter="24">
                <el-col :span="12">
                    <el-form-item label="货品类型名称" prop="goodsTypeName" required>
                        <el-input v-model="form.goodsTypeName" placeholder="请输入" class="full-width"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="排序" prop="sortOrder" required class="form-label ml-300">
                        <el-input v-model.number="form.sortOrder" placeholder="请输入" class="full-width"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <!-- 第二行：排序（左） + 状态（右） -->
            <el-row :gutter="20">

                <el-col :span="12">
                    <el-form-item label="状态" style="margin-top: 20px;">
                        <el-radio-group v-model="form.status">
                            <el-radio :label="1">启用</el-radio>
                            <el-radio :label="0">停用</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-col>
            </el-row>

            <!-- 第三行：备注（全宽） -->
            <el-row :gutter="20">
                <el-col :span="24">
                    <el-form-item label="备注" prop="remark">
                        <el-input v-model="form.remark" type="textarea" placeholder="请输入" rows="4" class="full-width"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>

            <!-- 提交/取消按钮 -->
            <el-form-item>
                <el-button type="primary" v-on:click="submitForm">提交</el-button>
                <el-button v-on:click="addDrawerVisible = false">取消</el-button>
            </el-form-item>
        </el-form>
    </el-drawer>
</div>

<style>
    /* 表格容器样式 */
    .table-container {
        width: 100%;
        margin: 0;
        overflow: hidden;
    }

    .form-label {
        white-space: nowrap;
        width: 220px;
        margin: 0;
    }

    /* 查询区域样式 */
    .search-area {
        margin: 10px 0;
        padding-top: 10px;
        display: flex;
        flex-wrap: wrap;
        align-items: center;
        gap: 6px;
    }

    /* 操作按钮区域 */
    .action-buttons {
        margin: 15px 0;
        padding-top: 5px;
    }

    .ml-300 {
        margin-left: 80px !important;
    }

    /* 震动动画定义 */
    v-on:keyframes shake {
        0%

    {
        transform: translateX(0);
    }

    20% {
        transform: translateX(-5px);
    }

    40% {
        transform: translateX(3px);
    }

    60% {
        transform: translateX(-2px);
    }

    80% {
        transform: translateX(2px);
    }

    100% {
        transform: translateX(0);
    }

    }

    .btn-shake {
        animation: shake 0.3s ease-in-out 1;
    }

    /* 输入框、下拉框等组件悬浮样式 */
    .el-input__wrapper:hover,
    .el-select .el-input__wrapper:hover,
    .el-date-editor.el-input__wrapper:hover {
        border-color: green !important;
        transition: border-color 0.2s ease-in-out;
        box-shadow: 0 0 0 2px rgba(103, 194, 53, 0.2) !important;
    }

    /* 按钮样式 */
    .query-btn {
        background-color: #409eff;
        color: white;
        border: none;
        padding: 4px 10px;
        cursor: pointer;
        font-size: 14px;
        transition: all 0.2s;
        margin-right: 8px;
        border-radius: 6px;
    }

        .query-btn:hover {
            background-color: #66b1ff;
            color: #ecf5ff;
        }

    .reset-btn {
        background-color: white;
        color: #606266;
        border: 1px solid #dcdfe6;
        padding: 4px 10px;
        cursor: pointer;
        font-size: 14px;
        transition: all 0.2s;
        margin-right: 8px;
        border-radius: 6px;
    }

        .reset-btn:hover {
            color: #67c23a;
            border-color: #67c23a;
            background-color: white;
        }

    /* 输入框样式 */
    .custom-input,
    .custom-select .el-input__wrapper {
        background-color: #fff !important;
        border-color: #dcdfe6 !important;
        border-radius: 4px;
        height: 32px;
    }

    .custom-select .el-input__inner {
        background-color: transparent !important;
    }

    /* 表格样式 */
    .el-table {
        width: 100% !important;
    }

    .el-table__header-wrapper .el-table__header {
        border-top: none !important;
    }

    .el-table__header th.el-table__cell {
        border-right: none !important;
        border-left: none !important;
        border-bottom: 1px solid #ebeef5 !important;
        border-top: none !important;
    }

    .el-table__body td.el-table__cell {
        border-right: none !important;
        border-left: none !important;
        border-bottom: 1px solid #ebeef5 !important;
    }

    /* 抽屉内表单整体间距 */
    .add-form {
        padding: 20px;
    }

    .full-width {
        width: 100%;
    }

    .el-form-item.is-required .el-form-item__label::before {
        content: "*";
        color: red;
        margin-right: 4px;
    }

    .el-radio {
        margin-right: 20px;
    }
</style>

<script>
    const { createApp, ref, reactive, watch } = Vue;
    const app = createApp({
        setup() {
            // 响应式数据
            const goodsTypeList = ref([]);
            const searchParams = ref({
                typeNameOrCode: "",
                status: "",
                updateBy: "",
                updateTimeRange: null, // 新增：存储 [开始日期, 结束日期]: null

            });
            // 分页相关数据
            const pagination = reactive({
            pageNum: 1,       // 当前页码（默认第1页）
            pageSize: 10,     // 每页条数（默认10条）
            total: 0          // 总记录数（从后端获取）
            });
            const isEdit = ref(false);
            const editItemData = ref({});
            const selectAll = ref(false);
            const loading = ref(false);
            // 新增：定义上传组件引用
            const uploadRef = ref(null);
            
            // 新增抽屉显示控制
            const addDrawerVisible = ref(false);

            // 表单数据
            const form = reactive({
                parentCategory: '',
                goodsTypeCode: '',
                goodsTypeName: '',
                sortOrder: '',
                status: 1,
                remark: ''
            });

            // 上级分类下拉选项
            const parentCategoryOptions = ref([]);

            // 监听goodsTypeList变化，动态生成上级分类选项
            watch(goodsTypeList, (newList) => {
                const generateOptions = (list, parentId = 0, level = 0, visited = new Set(), depth = 0) => {
                    // 增加深度限制，防止过深递归
                    if (depth > 20) return [];
                    if (visited.has(parentId)) return [];

                    visited.add(parentId);

                    return list
                        .filter(item => item.parentCategoryId === parentId)
                        .map(item => ({ ...item, level: level }))
                        .flatMap(item => [
                            item,
                            ...generateOptions(list, item.goodsTypeId, level + 1, new Set(visited), depth + 1)
                        ]);
                };
                parentCategoryOptions.value = generateOptions(newList);
            });

            // 按钮震动方法
            const triggerBtnShake = (btn) => {
                btn.classList.remove('btn-shake');
                void btn.offsetWidth;
                btn.classList.add('btn-shake');
                setTimeout(() => btn.classList.remove('btn-shake'), 300);
            };

            // 日期格式化
            const formatOperationTime = (row, column, cellValue) => {
                try {
                    if (!cellValue) return '-';
                    const date = new Date(cellValue);
                    if (isNaN(date.getTime())) return '-';
                    const year = date.getFullYear();
                    const month = String(date.getMonth() + 1).padStart(2, '0');
                    const day = String(date.getDate()).padStart(2, '0');
                    const hour = String(date.getHours()).padStart(2, '0');
                    const minute = String(date.getMinutes()).padStart(2, '0');
                    const second = String(date.getSeconds()).padStart(2, '0');
                    return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
                } catch (e) {
                    console.error('日期格式化失败：', e);
                    return '-';
                }
            };

            // 格式化货品类型名称（带层级缩进）
            const formatGoodsTypeName = (currentRow, allRows) => {
                let level = 0;
                let parentId = currentRow.parentCategoryId;
                let depth = 0;

                // 增加深度限制，防止无限循环
                while (parentId !== 0 && depth < 20) {
                    level++;
                    const parentRow = allRows.find(row => row.goodsTypeId === parentId);
                    if (!parentRow) break;
                    parentId = parentRow.parentCategoryId;
                    depth++;
                }

                const basePadding = 10
                const style = `padding-left: ${basePadding + level * 15}px;`;
                return `<span style="${style}">${currentRow.goodsTypeName || ''}</span>`;
            };

                // 处理查询参数（新增分页参数）
    const getQueryParams = () => {
      const params = {
        ...searchParams.value,
        pageNum: pagination.pageNum,   // 新增：当前页码
        pageSize: pagination.pageSize  // 新增：每页条数
      };

      // 原有参数处理逻辑不变...
      if (params.typeNameOrCode) params.typeNameOrCode = params.typeNameOrCode.trim();
      if (params.status === "") {
        params.status = null;
      } else {
        params.status = parseInt(params.status, 10);
      }
      if (params.updateTimeRange && params.updateTimeRange.length === 2) {
        params.startTime = params.updateTimeRange[0].toISOString().split('T')[0];
        params.endTime = params.updateTimeRange[1].toISOString().split('T')[0];
      }
      delete params.updateTimeRange;

      return params;
    };

                // 查询数据（适配分页）
    const queryData = (e) => {
      if (e) triggerBtnShake(e.target);
      loading.value = true;
      const params = getQueryParams();

      axios.get('/GoodsType/GoodsTypes', { params })
        .then(response => {
          console.log('分页数据:', response.data);
          // 假设后端返回 { total: 总条数, list: 当前页数据 }
          goodsTypeList.value = response.data.list;  // 绑定当前页数据
          pagination.total = response.data.total;    // 更新总记录数
          ElementPlus.ElMessage.success(`加载成功，共 ${pagination.total} 条数据`);
        })
        .catch(error => {
          console.error("获取数据失败：", error);
          ElementPlus.ElMessage.error("数据加载失败，请重试");
          goodsTypeList.value = [];
          pagination.total = 0;
        })
        .finally(() => loading.value = false);
    };
        // 每页条数变化时触发
    const handlePageSizeChange = (newSize) => {
      pagination.pageSize = newSize;  // 更新每页条数
      pagination.pageNum = 1;         // 重置为第1页
      queryData();                    // 重新查询
    };
        // 页码变化时触发
    const handlePageNumChange = (newPage) => {
      pagination.pageNum = newPage;   // 更新当前页码
      queryData();                    // 重新查询
    };
                const resetSearch = (e) => {
      triggerBtnShake(e.target);
      // 重置查询条件
      searchParams.value = {
        typeNameOrCode: "",
        status: "",
        updateBy: "",
        updateTimeRange: null
      };
      // 重置分页（回到第1页）
      pagination.pageNum = 1;
      pagination.pageSize = 10;
      // 重新查询
      setTimeout(queryData, 100);
    };

                // 编辑方法：确保回显时保留 GoodsTypeId，并在提交时传递
    const editItem = (item) => {

        console.log('编辑数据:', item);
    isEdit.value = true;
    // 存储当前编辑项的 ID（关键：用于后端定位记录）
    editItemData.value = { ...item };

    // 表单回显（补充非空校验）
    form.parentCategory = item.parentCategoryId || '';
    // 校验货品类型编号，若为空则提示（避免传递空值给后端）
    if (!item.goodsTypeCode) {
        ElementPlus.ElMessage.warning('数据异常：货品类型编号为空！');
        return;
    }
    form.goodsTypeCode = item.goodsTypeCode; // 确保非空
    form.goodsTypeName = item.goodsTypeName || '';
    form.sortOrder = item.sortOrder || 0; // 排序字段建议设为数字默认值
    form.status = item.status !== undefined ? item.status : 1;
    form.remarks = item.remarks || '';

    addDrawerVisible.value = true;
    };

            // 新增按钮点击事件
            const addNew = async () => {
                // 重置表单
                form.parentCategory = '';
                form.goodsTypeCode = '';
                form.goodsTypeName = '';
                form.sortOrder = '';
                form.status = 1;
                form.remarks = '';



                let numberLoading = null;
                try {
                    numberLoading = ElementPlus.ElLoading.service({
                        lock: true,
                        text: '正在生成编号...',
                        background: 'rgba(0, 0, 0, 0.3)'
                    });

                    const response = await axios.post('/NumberingRules/GenerateByRuleId',
                        {},
                        {
                            params: { ruleId: 1},
                            timeout: 5000
                        }
                    );
                    console.log('生成编号响应:', response.data); // 调试用
                    numberLoading.close();

                    if (response.data.success) {
                        form.goodsTypeCode = response.data.number;
                        addDrawerVisible.value = true;
                    } else {
                        ElementPlus.ElMessage.error(`编号生成失败：${response.data.message}`);
                    }
                } catch (error) {
                  if (numberLoading) numberLoading.close();
                  console.error('编号请求失败：', error);
                  // 更详细的错误提示，帮助定位问题
                  if (error.response && error.response.status === 404) {
                  ElementPlus.ElMessage.error('接口不存在，请检查请求路径是否正确');
                  } else {
                  ElementPlus.ElMessage.error('网络异常或系统错误，请重试');
                  }
                }
            };

            // 逻辑删除方法
            const deleteItem = (item) => {

                const typeName = item.goodsTypeName || '未知';
                const goodsTypeId = item.goodsTypeId;

                console.log('要删除的ID：', goodsTypeId);
                console.log('删除的数据：', item);

                ElementPlus.ElMessageBox.confirm(
                    `确定要删除“${typeName}”吗？`,
                    '删除确认',
                    { confirmButtonText: '确认', cancelButtonText: '取消', type: 'warning' }
                )
                .then(async () => {
                    try {
                        const response = await axios.put(
                            '/GoodsType/LogicalDelete',
                            {},
                            { params: { goodsTypeId: goodsTypeId } }
                        );

                        if (response.data.success) {
                            ElementPlus.ElMessage.success(response.data.message);
                            queryData();
                        } else {
                            ElementPlus.ElMessage.error(response.data.message);
                        }
                    } catch (error) {
                        console.error('删除请求失败：', error);
                        ElementPlus.ElMessage.error('删除接口请求失败，请重试');
                    }
                })
                .catch((error) => {
                    if (error === 'cancel' || error.name === 'Cancel') {
                        ElementPlus.ElMessage.info('已取消删除操作');
                    }
                });
            };

            // 提交表单
            const submitForm = () => {
                if (!form.goodsTypeName.trim()) {
                    ElementPlus.ElMessage.warning('请输入货品类型名称');
                    return;
                }

                if (!form.goodsTypeName.trim()) {
        ElementPlus.ElMessage.warning('请输入货品类型名称');
        return;
    }
    if (isEdit.value) {
        
         const editParams = {
            GoodsTypeId: editItemData.value.goodsTypeId,
            ParentCategoryId: form.parentCategory,  // 确保传递正确的字段名
            GoodsTypeCode: form.goodsTypeCode,
            GoodsTypeName: form.goodsTypeName,
            SortOrder: form.sortOrder,
            Status: form.status,
            Remarks: form.remarks
        };
        console.log('编辑提交参数:', editParams);
        // 调用编辑接口，传递包含 GoodsTypeId 的参数
        axios.put('/GoodsType/UpdateGoodsTypes', editParams)
            .then(() => {
                ElementPlus.ElMessage.success('编辑成功');
                addDrawerVisible.value = false;
                queryData();
                isEdit.value = false;
            })
            .catch(error => {
                console.error('编辑失败：', error);
                ElementPlus.ElMessage.error('编辑失败，请重试');
            });
                } else {
                    // 新增逻辑
                        // 前端 submitForm 方法中新增逻辑的请求
                       axios.put('/GoodsType/GetAddGoodsTypes', null, {
                       params: {
                       ParentCategoryId: form.parentCategoryId || '',  // 确保传递空字符串而非 undefined
                       GoodsTypeCode: form.goodsTypeCode,
                       GoodsTypeName: form.goodsTypeName,
                       SortOrder: form.sortOrder || 0,  // 提供默认值
                       Status: form.status || 1,
                       Remarks: form.remarks || ""
                       }
                    })
                      .then(response => {
                      console.log('新增成功', response.data);
                      ElementPlus.ElMessage.success('新增成功');
                      addDrawerVisible.value = false;
                      queryData();
                      // 新增成功后，调用更新流水号最大值接口
            const serialNumber = parseInt(form.goodsTypeCode.replace(/\D/g, ''), 10); // 从货品类型编号提取流水号
            axios.post('/NumberingRules/UpdateMaxAfterSuccess', null, {
                params: { ruleId: 1, currentSerial: serialNumber }
            }).then(updateRes => {
                console.log('更新流水号最大值响应:', updateRes.data);
                if (updateRes.data.success) {
                    console.log('流水号最大值更新成功');
                } else {
                    ElementPlus.ElMessage.warning(`流水号更新提示：${updateRes.data.message}`);
                }
            }).catch(updateErr => {
                console.error('更新流水号最大值失败:', updateErr);
                ElementPlus.ElMessage.error('更新流水号最大值接口调用失败');
            });
                      })
                     .catch(error => {
                     console.error('新增失败', error);
                     ElementPlus.ElMessage.error(`新增失败：${error.response?.data?.message || error.message}`);
                     });
                }
            };

                // 导入相关数据
    const importDialogVisible = ref(false);
    const excelFile = ref(null); // 存储选中的Excel文件

    // 打开导入弹窗
        const openImportDialog = () => {
            importDialogVisible.value = true;
            excelFile.value = null;
            uploadRef.value?.clearFiles(); // 清空文件列表
        };

        // 选择文件时触发
        const handleFileChange = (file) => {
            if (file.size > 5 * 1024 * 1024) { // 5MB限制
                ElementPlus.ElMessage.error("文件大小不能超过5MB");
                return false;
            }
            excelFile.value = file.raw; // 保存文件
        };

        // 确认导入
        const confirmImport = async () => {
            if (!excelFile.value) {
                ElementPlus.ElMessage.warning("请选择文件");
                return;
            }

            const formData = new FormData();
            formData.append("file", excelFile.value);

            try {
                loading.value = true;
                const res = await axios.post("/GoodsType/Import", formData, {
                    headers: { "Content-Type": "multipart/form-data" }
                });
                ElementPlus.ElMessage.success(`导入成功：${res.data.message}`);
                importDialogVisible.value = false;
                queryData(); // 重新加载数据
            } catch (err) {
                ElementPlus.ElMessage.error(`导入失败：${err.response?.data?.message || err.message}`);
            } finally {
                loading.value = false;
            }
        };

        // 导出数据
        const exportData = async () => {
            try {
                loading.value = true;
                const res = await axios.get("/GoodsType/Export", {
                    responseType: "blob", // 关键：接收二进制流
                    params: { /* 可携带筛选参数，如状态、时间范围等 */ }
                });

                // 处理文件流下载
                const blob = new Blob([res.data], {
                    type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
                });
                const url = URL.createObjectURL(blob);
                const a = document.createElement("a");
                a.href = url;
                a.download = `货品类型_${new Date().toLocaleDateString()}.xlsx`;
                a.click();
                URL.revokeObjectURL(url); // 释放资源
                ElementPlus.ElMessage.success("导出成功");
            } catch (err) {
                ElementPlus.ElMessage.error(`导出失败：${err.message}`);
            } finally {
                loading.value = false;
            }
        };

            // 页面加载时自动查询数据
            queryData();

            return {
                goodsTypeList,
                searchParams,
                selectAll,
                loading,
                addDrawerVisible,
                form,
                parentCategoryOptions,
                isEdit,
                editItemData,
                queryData,
                resetSearch,
                addNew,
                openImportDialog,
                handleFileChange,
                confirmImport,
                exportData,
                editItem,
                uploadRef,
                deleteItem,
                formatOperationTime,
                formatGoodsTypeName,
                submitForm,
                importDialogVisible,
                pagination,                  // 分页数据对象（含pageNum、pageSize、total）
                handlePageSizeChange,           // 每页数变化事件
                handlePageNumChange          // 页码变化事件
            };
        }
    });
    app.use(ElementPlus);
    app.mount("#app");
</script>
